using System;
using Microsoft.Maui.Controls;

namespace planning_lite
{
    public partial class FilterPage : ContentPage
    {
        private TaskFilter _filter;

        // 用于绑定的属性
        public bool ShowCompleted { get; set; }
        public bool ShowObsolete { get; set; }
        public bool HasDueDate { get; set; }
        public DateTime DueDate { get; set; }
        public int Priority { get; set; }
        public DateTime MinDate { get; } = DateTime.Today;
        public bool sortByDueDate { get; set; }
        public bool sortByPriority { get; set; }

        public FilterPage(TaskFilter filter)
        {
            InitializeComponent();

            // 从现有过滤器复制设置
            _filter = filter;
            ShowCompleted = filter.ShowCompleted;
            ShowObsolete = filter.ShowObsolete;
            HasDueDate = filter.DueDate.HasValue;
            DueDate = filter.DueDate ?? DateTime.Today;
            Priority = filter.Priority;
            sortByDueDate = filter.sortByDueDate;
            sortByPriority = filter.sortByPriority;

            BindingContext = this;
        }

        private void OnDueDateFilterToggled(object sender, ToggledEventArgs e)
        {
            // 更新截止日期容器的可见性
            HasDueDate = e.Value;
            DueDateContainer.IsVisible = e.Value;
        }

        private async void OnCancelClicked(object sender, EventArgs e)
        {
            // 关闭页面而不应用更改
            await Navigation.PopAsync();
        }

        private async void OnApplyClicked(object sender, EventArgs e)
        {
            // 将设置应用到过滤器
            _filter.ShowCompleted = ShowCompleted;
            _filter.ShowObsolete = ShowObsolete;
            _filter.DueDate = HasDueDate ? DueDate : null;
            _filter.Priority = Priority;
            _filter.sortByDueDate = sortByDueDate;
            _filter.sortByPriority = sortByPriority;

            // 返回并刷新任务列表
            await Navigation.PopAsync();

            // 触发任务列表更新
            if (MainPage.OnTasksUpdate != null)
            {
                MainPage.Filter = _filter;
                MainPage.OnTasksUpdate();
            }
        }

        private void OnPrioritySliderValueChanged(object sender, ValueChangedEventArgs e)
        {
            Priority = (int)e.NewValue;
            PriorityValueLabel.Text = Priority.ToString();
        }

    }
}